package com.xm.data.config;

import com.xm.data.entiry.StatType;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Slf4j
public class TableInitializer {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static final int[] GRANULARITIES = {1,5,10,20,60,120,360,720};

    @PostConstruct
    public void initTables() {
        Arrays.stream(StatType.values()).forEach(type -> {
            Arrays.stream(GRANULARITIES).forEach(granularity -> {
                createTableIfNotExists(type, granularity);
            });
        });
    }

    public void createTableIfNotExists(StatType type, int granularity) {
        String tableName = generateTableName(type, granularity);
        if (!tableExists(tableName)) {
            String ddl = buildCreateTableDDL(type, granularity, tableName);
            executeDDL(ddl, tableName);
        }
    }

    private String buildCreateTableDDL(StatType type, int granularity, String tableName) {
        return String.format("""
            CREATE TABLE IF NOT EXISTS `%s` (
              `id` BIGINT NOT NULL AUTO_INCREMENT,
              `client_id` VARCHAR(36) NOT NULL COMMENT '客户端ID',
              `timestamp` BIGINT NOT NULL COMMENT '时间戳（毫秒）',
              `cpu_usage` DOUBLE DEFAULT 0.0,
              `memory_usage` DOUBLE DEFAULT 0.0,
              `disk_usage` DOUBLE DEFAULT 0.0,
              `network_upload` DOUBLE DEFAULT 0.0,
              `network_download` DOUBLE DEFAULT 0.0,
              `disk_write` DOUBLE DEFAULT 0.0,
              `disk_read` DOUBLE DEFAULT 0.0,
              PRIMARY KEY (`id`),
              UNIQUE KEY `udx_client_time` (`client_id`,`timestamp`),
              KEY `idx_client_id` (`client_id`),
              KEY `idx_timestamp` (`timestamp`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
            COMMENT '%s统计表（%d分钟粒度）'
            AUTO_INCREMENT=100001;
            """, tableName, type.getDescription(), granularity);
    }

    private void executeDDL(String ddl, String tableName) {
        try {
            jdbcTemplate.execute(ddl);
            log.info("成功创建表：{}", tableName);
        } catch (DataAccessException e) {
            log.error("建表失败：{} | 错误：{}", tableName, e.getCause().getMessage());
        }
    }

    private boolean tableExists(String tableName) {
        try {
            jdbcTemplate.execute("SELECT 1 FROM " + tableName + " LIMIT 1");
            return true;
        } catch (BadSqlGrammarException e) {
            return e.getSQLException().getErrorCode() != 1146;
        }
    }

    public static String generateTableName(StatType type, int granularity) {
        return String.format("history_%s_%dm",
                type.name().toLowerCase(),
                granularity);
    }
}
